package tp.igl.View;


import javafx.animation.FadeTransition;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.util.Duration;
import tp.igl.AdresseIP;
import tp.igl.Masque;
import tp.igl.Reseau;
import tp.igl.Segment;

/**
 * <p>Génère le conteneur principal (root) de la Scene</p>
 * @author PNR KACIMI HACINI
 */
public class Root extends VBox {

    private AdresseIpField adresse;
    private MasqueField masque;
    private Reseau reseau;
    
    /**
     *Constructeur Root
     */
    public Root(){
        
         super(20); 
         setAlignment(Pos.CENTER);
         AdresseIP ip=new AdresseIP(new Segment(192), new Segment(192), new Segment(192), new Segment(192));
         Masque masqueF=new Masque(new Segment(255), new Segment(255), new Segment(252), new Segment(0));
         getStylesheets().add(getClass().getResource("CSS.css").toExternalForm());
         adresse=new AdresseIpField(ip);
         masque=new MasqueField(masqueF);

         reseau=new Reseau(ip, masqueF);
         final Integer nbSub=new Integer(0);
         
         final TabContainer result=new TabContainer(reseau);
         
         VBox titres=new VBox(20);
         Label L1=new Label();L1.setText("IP Adress");L1.setMinSize(USE_PREF_SIZE, USE_PREF_SIZE);
         Label L2=new Label();L2.setText("Mask");
         
         titres.getChildren().addAll(L1,L2);
         titres.setAlignment(Pos.CENTER);
         titres.autosize();
         titres.setFillWidth(true);
         
         VBox valeurs=new VBox(20);
         valeurs.getChildren().add(adresse);
         valeurs.getChildren().add(masque);
         
         HBox total=new HBox();
         total.getChildren().addAll(titres,valeurs);
         total.setMaxWidth(270);
         final Button go=new Button("Calculate");
         
         
         go.setMinHeight(30);go.setMaxHeight(30);
        final TextField numberField = new TextField("8") {
        @Override public void replaceText(int start, int end, String text) {
          if (text.matches("[0-9]*")) {
            super.replaceText(start, end, text);
          }
        }

          @Override
          public void replaceSelection(String text) {
              if (text.matches("[0-9]*")) {
                super.replaceSelection(text);
              }
            }
          

          };


         //         go.setStyle("-fxdisplay: inline-block;-fx-margin: 0;-fx-padding: 7px 14px;-fx-border: 1px solid transparent;-fx-border-radius: 2px;-fx-color: #ffffff;-fx-vertical-align: middle;text-align: center;-fx-font-weight: bold;-fx-font-size: 13px;-fx-font-family: Arial ;-fx-line-height: 1.5384615384615385;-fx-cursor: pointer;-fx-outline: none;-fx-background-color: #434a54;-fx-border-color: #434a54;");
         ImageView logo=new ImageView(new Image(getClass().getResourceAsStream("logo2.png")));
         numberField.setAlignment(Pos.CENTER);
         numberField.setMinSize(40, 25);
         numberField.setMaxSize(40, 25);
         HBox subInfo=new HBox(20);
         final CheckBox check=new CheckBox();
         Label checkText=new Label("Sub-Networking");
         checkText.setStyle("-fx-text-fill:#d1d1d1;-fx-font-size: 12px;");
         final HBox checkBox=new HBox(5);
         checkBox.getChildren().addAll(check,checkText);
         check.setSelected(false);
         
         numberField.setDisable(true);
         
         final ScrollPane subs=new ScrollPane();
         subs.setStyle("-fx-background-color:#1B1B1B;");
         
         final SubNetAccordion accordion=new SubNetAccordion(reseau.getSubetworks(nbSub.intValue()));
         accordion.setMaxWidth(tp.igl.TPIGL.width);
         accordion.setMinWidth(tp.igl.TPIGL.width);
         accordion.setLayoutX(10);
         subs.setContent(accordion);
            check.selectedProperty().addListener(new ChangeListener<Boolean>() {
            @Override
            public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
                if (check.isSelected()){
                    numberField.setDisable(false);
                    numberField.fireEvent(new ActionEvent());   
                    result.getTabs().add(new ResultTab(subs));
                }
                else {
                    numberField.setDisable(true);
                    result.getTabs().remove(3);
                    
                }
            }
        });
         
         subInfo.getChildren().addAll(checkBox,numberField);
         checkBox.setAlignment(Pos.CENTER);
         subInfo.setAlignment(Pos.CENTER);
         this.getChildren().addAll(logo,total,subInfo,go,result);

         setHeight(tp.igl.TPIGL.height);
         setStyle("-fx-background-color:#1B1B1B");
         
         // gérer les evenements
         

          // controller le contenue du textField
          numberField.setOnAction(new EventHandler<ActionEvent>(){
             @Override
             public void handle(ActionEvent t) {
                 TextField source=(TextField)t.getSource();
                 if(source.getText().length()==0)
                     source.setText("1");
                 Integer nb=Reseau.arronderNombre(Integer.parseInt(source.getText()));
                 if(nb>reseau.getNbrMaxSubNets()){
                     nb=reseau.getNbrMaxSubNets();
                 }
                 
                 if(nb<1)
                 nb=1;
                 source.setText(nb.toString()); 
                 go.fire();
             }
         });
          
         numberField.focusedProperty().addListener(new ChangeListener<Boolean>(){

             @Override
             public void changed(ObservableValue<? extends Boolean> ov, Boolean t, Boolean t1) {
                if(!t1){
                   numberField.fireEvent(new ActionEvent()); // appele la methode handle
               }
             }
         });
          
         masque.setOnAction(new EventHandler<ActionEvent>() {
             @Override
             public void handle(ActionEvent t) {
                 if(masque.getAdresse().getAdresse()[3].getValeur()>252){
                      masque.getListeDesSegements().get(3).setText("252"); 
                      masque.getAdresse().getAdresse()[3].setValeur(252);
                 }

                 if(check.isSelected()){
                    numberField.fireEvent(new ActionEvent());
                 }else{
                    go.fire(); 
                 }
             }
         });
         
         adresse.setOnAction(new EventHandler<ActionEvent>() {
             @Override
             public void handle(ActionEvent t) {
                 go.fire();
             }
         });
         
         go.setOnAction(new EventHandler<ActionEvent>() {
         int[] nbSubs=new int[]{nbSub.intValue()};
            @Override
            public void handle(ActionEvent t) {

                reseau.refresh(adresse.toAdresseIP(), masque.toMasque());
                result.refresh(reseau);
                if(check.isSelected()){
                   nbSubs[0]=Integer.parseInt(numberField.getText());
                   accordion.refresh(reseau.getSubetworks(nbSubs[0]));
                }
                
            }
        });
         FadeTransition ft = new FadeTransition();
                    ft.setNode(this);
                    ft.setDuration(Duration.millis(2050));
                    ft.setFromValue(0);
                    ft.setToValue(1.0);
                    ft.setCycleCount(1);
                    ft.play();
    }
}
